//
//  CYFinanceCell.m
//  cyjf
//
//  Created by tauCross on 2017/5/5.
//  Copyright © 2017年 Auto Financing. All rights reserved.
//

#import "CYFinanceCell.h"

#import "CYGlobalTimerManager.h"



@implementation CYFinanceCellObject

@end



@interface CYFinanceCell ()

@property(nonatomic, strong)UIImageView *highlightHeaderBG;
@property(nonatomic, strong)UIImageView *rushIcon;

@property(nonatomic, strong)UILabel *titleLabel;
@property(nonatomic, strong)UILabel *tagLabel;
@property(nonatomic, strong)CAShapeLayer *tagBorder;
@property(nonatomic, strong)UILabel *additionRateLabel;
@property(nonatomic, strong)UIImageView *additionRateBackgroundImageView;
@property(nonatomic, strong)CAShapeLayer *additionRateBorder;
@property(nonatomic, strong)UIImageView *line;
@property(nonatomic, strong)UILabel *rateLabel;
@property(nonatomic, strong)UILabel *rateDescLabel;
@property(nonatomic, strong)UILabel *dueLabel;
@property(nonatomic, strong)UIImageView *progressBackground;
@property(nonatomic, strong)UIImageView *progress;
@property(nonatomic, strong)UILabel *progressLabel;
@property(nonatomic, strong)UILabel *disableLabel;

@property(nonatomic, strong)UIView *countDownView;
@property(nonatomic, strong)UIImageView *countDownImageView;
@property(nonatomic, strong)UILabel *countDownLabel;
@property(nonatomic, strong)UILabel *hourLabel;
@property(nonatomic, strong)UILabel *minLabel;
@property(nonatomic, strong)UILabel *secLabel;
@property(nonatomic, strong)UIImageView *c1ImageView;
@property(nonatomic, strong)UIImageView *c2ImageView;

@property(nonatomic, strong)CYFinanceCellObject *object;

@property(nonatomic, strong)UIImage *additionImageDefault;
@property(nonatomic, strong)UIImage *additionImageDisable;

@end


@implementation CYFinanceCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if(self)
    {
        self.backgroundColor = [UIColor clearColor];
        self.contentView.backgroundColor = [UIColor whiteColor];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        
        self.highlightHeaderBG = [[UIImageView alloc] initWithImage:CYImage(@"bg_finance_item_title")];
        [self.contentView addSubview:self.highlightHeaderBG];
        
        self.titleLabel = [[UILabel alloc] init];
        self.titleLabel.font = [UIFont systemFontOfSize:14];
        [self.contentView addSubview:self.titleLabel];
        
        self.tagLabel = [[UILabel alloc] init];
        self.tagLabel.font = [UIFont systemFontOfSize:10 weight:UIFontWeightRegular];
        self.tagLabel.textAlignment = NSTextAlignmentCenter;
        [self.contentView addSubview:self.tagLabel];
        
        self.tagBorder = [[CAShapeLayer alloc] init];
        self.tagBorder.lineWidth = 1 / SCREEN_SCALE;
        self.tagBorder.fillColor = [UIColor clearColor].CGColor;
        [self.tagLabel.layer addSublayer:self.tagBorder];
        
        self.additionRateBackgroundImageView = [[UIImageView alloc] init];
        [self.contentView addSubview:self.additionRateBackgroundImageView];
        
        self.additionRateBorder = [[CAShapeLayer alloc] init];
        self.additionRateBackgroundImageView.layer.mask = self.additionRateBorder;
        
        self.additionRateLabel = [[UILabel alloc] init];
        self.additionRateLabel.textColor = HEXCOLOR(@"ffffff");
        self.additionRateLabel.font = [UIFont systemFontOfSize:10 weight:UIFontWeightRegular];
        [self.contentView addSubview:self.additionRateLabel];

        self.line = [UIImageView cy_imageLineWithColor:HEXCOLOR(@"ECECEC")];
        [self.contentView addSubview:self.line];
        
        self.rateLabel = [[UILabel alloc] init];
        self.rateLabel.font = [UIFont systemFontOfSize:24 weight:UIFontWeightRegular];
        [self.contentView addSubview:self.rateLabel];
        
        self.rateDescLabel = [[UILabel alloc] init];
        self.rateDescLabel.font = [UIFont systemFontOfSize:12];
        self.rateDescLabel.text = @"预期年化收益率";
        [self.rateDescLabel sizeToFit];
        [self.contentView addSubview:self.rateDescLabel];
        
        self.dueLabel = [[UILabel alloc] init];
        self.dueLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightRegular];
        [self.contentView addSubview:self.dueLabel];
        
        self.progressBackground = [[UIImageView alloc] initWithImage:[UIImage imageWithColor:HEXCOLOR(@"ECECEC") size:CGSizeMake(85, 2)]];
        [self.contentView addSubview:self.progressBackground];
        
        self.progress = [[UIImageView alloc] init];
        self.progress.image = [UIImage gradientImageFromColors:@[HEXCOLOR(@"FE754D"), HEXCOLOR(@"FEDFC4")] ByGradientType:UIImageGradientTypeLeftToRight size:CGSizeMake(SCREEN_WIDTH, 3)];
        [self.contentView addSubview:self.progress];
        
        self.progressLabel = [[UILabel alloc] init];
        self.progressLabel.textColor = HEXCOLOR(@"999999");
        self.progressLabel.font = [UIFont systemFontOfSize:12];
        [self.contentView addSubview:self.progressLabel];
        
        self.disableLabel = [[UILabel alloc] init];
        self.disableLabel.font = [UIFont systemFontOfSize:12];
        self.disableLabel.textColor = HEXCOLOR(@"CCCCCC");
        [self.contentView addSubview:self.disableLabel];
        
        self.countDownView = [[UIView alloc] init];
        self.countDownView.backgroundColor = HEXCOLOR(@"FFFBEA");
        [self.contentView addSubview:self.countDownView];
        {
            self.countDownImageView = [[UIImageView alloc] initWithImage:CYImage(@"ico_countdown_clock")];
            [self.countDownView addSubview:self.countDownImageView];
            
            self.countDownLabel = [[UILabel alloc] init];
            self.countDownLabel.text = @"距开抢还剩";
            self.countDownLabel.textColor = HEXCOLOR(@"FFA82A");;
            self.countDownLabel.font = [UIFont systemFontOfSize:12 weight:UIFontWeightRegular];
            [self.countDownLabel sizeToFit];
            [self.countDownView addSubview:self.countDownLabel];
            
            self.hourLabel = ({
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 18, 20)];
                label.textColor = HEXCOLOR(@"FFFBEA");
                label.font = [UIFont systemFontOfSize:11 weight:UIFontWeightRegular];
                label.backgroundColor = HEXCOLOR(@"FFA82A");
                label.layer.masksToBounds = YES;
                label.layer.cornerRadius = 3;
                label.textAlignment = NSTextAlignmentCenter;
                label;
            });
            [self.countDownView addSubview:self.hourLabel];
            
            self.minLabel = ({
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 18, 20)];
                label.textColor = HEXCOLOR(@"FFFBEA");
                label.font = [UIFont systemFontOfSize:11 weight:UIFontWeightRegular];
                label.backgroundColor = HEXCOLOR(@"FFA82A");
                label.layer.masksToBounds = YES;
                label.layer.cornerRadius = 3;
                label.textAlignment = NSTextAlignmentCenter;
                label;
            });
            [self.countDownView addSubview:self.minLabel];
            
            self.secLabel = ({
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 18, 20)];
                label.textColor = HEXCOLOR(@"FFFBEA");
                label.font = [UIFont systemFontOfSize:11 weight:UIFontWeightRegular];
                label.backgroundColor = HEXCOLOR(@"FFA82A");
                label.layer.masksToBounds = YES;
                label.layer.cornerRadius = 3;
                label.textAlignment = NSTextAlignmentCenter;
                label;
            });
            [self.countDownView addSubview:self.secLabel];
            
            self.c1ImageView = [[UIImageView alloc] initWithImage:CYImage(@"ico_countdown_colon")];
            [self.countDownView addSubview:self.c1ImageView];
            
            self.c2ImageView = [[UIImageView alloc] initWithImage:CYImage(@"ico_countdown_colon")];
            [self.countDownView addSubview:self.c2ImageView];
        }
        
        self.additionImageDefault = [UIImage gradientImageFromColors:@[HEXCOLOR(@"F7694E"), APP_DEFAULT_COLOR_RED] ByGradientType:UIImageGradientTypeLeftToRight size:CGSizeMake(100, 15 + 2 / SCREEN_SCALE)];
        self.additionImageDisable = [UIImage imageWithColor:HEXCOLOR(@"E1E1E1") size:CGSizeMake(100, 15 + 2 / SCREEN_SCALE)];
        
        self.rushIcon = [[UIImageView alloc] initWithImage:CYImage(@"ico_finace_item_title_tag_qiang")];
        [self.contentView addSubview:self.rushIcon];
    }
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];
    self.countDownView.backgroundColor = HEXCOLOR(@"FFFBEA");
    self.hourLabel.backgroundColor = HEXCOLOR(@"FFA82A");
    self.minLabel.backgroundColor = HEXCOLOR(@"FFA82A");
    self.secLabel.backgroundColor = HEXCOLOR(@"FFA82A");
}

- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated
{
    [super setHighlighted:highlighted animated:animated];
    self.countDownView.backgroundColor = HEXCOLOR(@"FFFBEA");
    self.hourLabel.backgroundColor = HEXCOLOR(@"FFA82A");
    self.minLabel.backgroundColor = HEXCOLOR(@"FFA82A");
    self.secLabel.backgroundColor = HEXCOLOR(@"FFA82A");
}

+ (CGFloat)heightForObject:(CYFinanceCellObject *)object atIndexPath:(NSIndexPath *)indexPath tableView:(UITableView *)tableView
{
    return 135 + (([object.model.saleDate timeIntervalSinceNow] >= 0 && object.model.status == CYFinanceViewModelStatusWillSale) ? 40 : 0);
}

- (BOOL)shouldUpdateCellWithObject:(id)object
{
    self.object = object;
    
    [CYStandardGlobalTimerManager removeTarget:self];
    
    NSString *tag = SAFE_STRING(self.object.model.tag);
    if(tag.length)
    {
        self.tagLabel.hidden = NO;
        self.tagLabel.text = tag;
    }
    else
    {
        self.tagLabel.hidden = YES;
    }
    
    double additionRate = SAFE_STRING(self.object.model.additionRate).doubleValue;
    if(additionRate > 0)
    {
        self.additionRateLabel.hidden = NO;
        self.additionRateBackgroundImageView.hidden = NO;
        self.additionRateLabel.text = [NSString stringWithFormat:@"已贴息%.2f%%", additionRate];
    }
    else
    {
        self.additionRateLabel.hidden = YES;
        self.additionRateBackgroundImageView.hidden = YES;
    }
    
    self.titleLabel.text = self.object.model.title;
    self.rateLabel.text = [NSString stringWithFormat:@"%.2f%%", SAFE_STRING(self.object.model.rate).doubleValue + SAFE_STRING(self.object.model.additionRate).doubleValue];

    self.progressBackground.hidden = YES;
    self.progress.hidden = YES;
    self.progressLabel.hidden = YES;
    self.disableLabel.hidden = YES;
    self.countDownView.hidden = YES;
    
    switch(self.object.model.status)
    {
        case CYFinanceViewModelStatusOnSale:
        {
            self.titleLabel.textColor = HEXCOLOR(@"444444");
            self.rateDescLabel.textColor = HEXCOLOR(@"999999");
            self.dueLabel.textColor = HEXCOLOR(@"444444");
            self.rateLabel.textColor = APP_DEFAULT_COLOR_RED;
            self.dueLabel.text = [self.object.model.due stringByAppendingString:@"天期限"];
            
            self.progressBackground.hidden = NO;
            self.progress.hidden = NO;
            self.progress.height = 2;
            self.progress.width = self.progressBackground.width * (self.object.model.perCent.doubleValue / 100);
            self.progressLabel.hidden = NO;
            self.progressLabel.text = [NSString stringWithFormat:@"已售%@%%", self.object.model.perCent];
            
            self.tagLabel.textColor = APP_DEFAULT_COLOR_RED;
            self.tagBorder.strokeColor = APP_DEFAULT_COLOR_RED.CGColor;
            
            self.additionRateBackgroundImageView.image = self.additionImageDefault;

            break;
        }
        case CYFinanceViewModelStatusWillSale:
        {
            self.progressBackground.hidden = NO;
            self.progress.hidden = NO;
            self.progress.height = 2;
            self.progress.width = 0;
            self.progressLabel.hidden = NO;
            self.progressLabel.text = @"已售0%";

            self.titleLabel.textColor = HEXCOLOR(@"444444");
            self.rateDescLabel.textColor = HEXCOLOR(@"999999");
            self.rateLabel.textColor = APP_DEFAULT_COLOR_RED;
            self.dueLabel.textColor = HEXCOLOR(@"444444");
            self.dueLabel.text = [self.object.model.due stringByAppendingString:@"天期限"];

            NSTimeInterval timeInterval = [self.object.model.saleDate timeIntervalSinceNow];
            if(timeInterval < 0)
            {
                self.object.model.status = CYFinanceViewModelStatusOnSale;
                if(self.object.reloadTableView)
                {
                    self.object.reloadTableView();
                }
            }
            else
            {
                self.countDownView.hidden = NO;
                
                NSString *time = [self.object.model.saleDate cy_financeCountDown];
                self.hourLabel.text = [time componentsSeparatedByString:@":"][0];
                self.minLabel.text = [time componentsSeparatedByString:@":"][1];
                self.secLabel.text = [time componentsSeparatedByString:@":"][2];
                
                @weakify(self);
                [CYStandardGlobalTimerManager addTarget:self withBlock:^{
                    @strongify(self);
                    [self shouldUpdateCellWithObject:self.object];
                    [self layoutIfNeeded];
                }];
            }
            
            self.tagLabel.textColor = APP_DEFAULT_COLOR_RED;
            self.tagBorder.strokeColor = APP_DEFAULT_COLOR_RED.CGColor;
            
            self.additionRateBackgroundImageView.image = self.additionImageDefault;
            
            break;
        }
        case CYFinanceViewModelStatusFull:
        {
            self.titleLabel.textColor = HEXCOLOR(@"CCCCCC");
            self.rateDescLabel.textColor = HEXCOLOR(@"CCCCCC");
            self.rateLabel.textColor = HEXCOLOR(@"CCCCCC");
            self.dueLabel.textColor = HEXCOLOR(@"CCCCCC");
            self.dueLabel.text = [self.object.model.due stringByAppendingString:@"天期限"];

            self.disableLabel.hidden = NO;
            self.disableLabel.text = @"已满标";
            
            self.tagLabel.textColor = HEXCOLOR(@"CCCCCC");
            self.tagBorder.strokeColor = HEXCOLOR(@"CCCCCC").CGColor;
            
            self.additionRateBackgroundImageView.image = self.additionImageDisable;

            break;
        }
        case CYFinanceViewModelStatusDone:
        {
            self.titleLabel.textColor = HEXCOLOR(@"CCCCCC");
            self.rateDescLabel.textColor = HEXCOLOR(@"CCCCCC");
            self.rateLabel.textColor = HEXCOLOR(@"CCCCCC");
            self.dueLabel.textColor = HEXCOLOR(@"CCCCCC");
            self.dueLabel.text = [self.object.model.due stringByAppendingString:@"天期限"];

            self.disableLabel.hidden = NO;
            self.disableLabel.text = @"已还款";

            self.tagLabel.textColor = HEXCOLOR(@"CCCCCC");
            self.tagBorder.strokeColor = HEXCOLOR(@"CCCCCC").CGColor;
            
            self.additionRateBackgroundImageView.image = self.additionImageDisable;

            break;
        }
    }
    
    BOOL rushFlag = (SAFE_NUMBER(self.object.model.apiModel.isRush).boolValue && self.object.model.status != CYFinanceViewModelStatusFull && self.object.model.status != CYFinanceViewModelStatusDone);
    self.highlightHeaderBG.hidden = !rushFlag;
    self.rushIcon.hidden = !rushFlag;
    
    [self setNeedsLayout];
    return YES;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    BOOL rushFlag = (SAFE_NUMBER(self.object.model.apiModel.isRush).boolValue && self.object.model.status != CYFinanceViewModelStatusFull && self.object.model.status != CYFinanceViewModelStatusDone);

    if(rushFlag)
    {
        self.contentView.height -= 1;
        self.contentView.top = 1;
    }
    
    self.highlightHeaderBG.width = self.contentView.width;
    self.highlightHeaderBG.height = 44;
    
    self.rushIcon.right = self.contentView.width - 8;
    self.rushIcon.top = -1;
    
    CGFloat space = SCREEN_WIDTH == 320 ? 10 : 20;
    
    [self.titleLabel sizeToFit];
    self.titleLabel.left = space;
    self.titleLabel.centerY = 22;
    
    [self.tagLabel sizeToFit];
    self.tagLabel.centerY = 22;
    self.tagBorder.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, self.tagLabel.width + (self.additionRateLabel.hidden ? 12 : 16), 15) byRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(5, 5)].CGPath;
    self.tagBorder.frame = CGRectMake(-6, (self.tagLabel.height - 15) / 2, self.tagLabel.width + (self.additionRateLabel.hidden ? 12 : 16), 15);

    [self.additionRateLabel sizeToFit];
    self.additionRateBackgroundImageView.height = 15 + 2 / SCREEN_SCALE;
    self.additionRateBackgroundImageView.width = self.additionRateLabel.width + 12;
    self.additionRateBackgroundImageView.centerY = self.titleLabel.centerY;

    self.additionRateBorder.path = [UIBezierPath bezierPathWithRoundedRect:self.additionRateBackgroundImageView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(5, 5)].CGPath;
    self.additionRateBorder.frame = self.additionRateBackgroundImageView.bounds;
    
    CGFloat width = self.titleLabel.width;
    
    if(self.tagLabel.hidden == NO)
    {
        width += self.tagLabel.width + 11;
        if(self.additionRateBackgroundImageView.hidden == NO)
        {
            width += self.additionRateBackgroundImageView.width + 5;
        }
    }
    else if(self.additionRateBackgroundImageView.hidden == NO)
    {
        width += self.additionRateBackgroundImageView.width + 5;
    }
    
    CGFloat maxWidth = self.contentView.width - space - (rushFlag ? 48 : space);
    
    if(width > maxWidth)
    {
        self.titleLabel.width -= (width - maxWidth);
    }
    
    self.titleLabel.left = space;
    self.tagLabel.left = self.titleLabel.right + 11;
    if(self.tagLabel.hidden)
    {
        self.additionRateBackgroundImageView.left = self.titleLabel.right + 5;
    }
    else
    {
        self.additionRateBackgroundImageView.left = self.tagLabel.right + 5;
    }

    self.additionRateLabel.center = self.additionRateBackgroundImageView.center;
    
    self.line.width = self.contentView.width - space;
    self.line.height = 1 / SCREEN_SCALE;
    self.line.left = space;
    self.line.bottom = 44;
    
    [self.rateLabel sizeToFit];
    self.rateLabel.left = space;
    self.rateLabel.centerY = 78;
    
    self.rateDescLabel.left = space;
    self.rateDescLabel.centerY = 106;
    
    [self.dueLabel sizeToFit];
    self.dueLabel.left = self.contentView.width / 2;
    self.dueLabel.centerY = 85;

    self.progressBackground.left = self.contentView.width / 2;
    self.progressBackground.top = 106;
    
    self.progress.left = self.progressBackground.left;
    self.progress.top = self.progressBackground.top;
    
    [self.progressLabel sizeToFit];
    self.progressLabel.centerY = self.progressBackground.centerY;
    self.progressLabel.left = self.progressBackground.right + 5;
    
    [self.disableLabel sizeToFit];
    self.disableLabel.left = self.contentView.width / 2;
    self.disableLabel.centerY = 106;
    
    self.countDownView.width = self.contentView.width;
    self.countDownView.height = 40;
    self.countDownView.left = 0;
    self.countDownView.top = 135;
    {
        self.countDownLabel.centerY = self.countDownView.height / 2;
        self.countDownLabel.right = self.countDownView.width - 90;
        
        self.countDownImageView.centerY = self.countDownView.height / 2;
        self.countDownImageView.right = self.countDownLabel.left - 5;
        
        self.hourLabel.centerY = self.minLabel.centerY = self.secLabel.centerY = self.countDownView.height / 2;
        self.hourLabel.right = self.countDownView.width - 65;
        self.minLabel.right = self.countDownView.width - 39;
        self.secLabel.right = self.countDownView.width - 13;
        
        self.c1ImageView.centerY = self.c2ImageView.centerY = self.countDownView.height / 2;
        self.c1ImageView.centerX = self.hourLabel.right + (self.minLabel.left - self.hourLabel.right) / 2;
        self.c2ImageView.centerX = self.minLabel.right + (self.secLabel.left - self.minLabel.right) / 2;
    }
}

@end
